package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.GoToOrderBean;
import com.wnhz.work.yz.bean.JsonBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.GetJsonDataUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;
import com.wnhz.work.yz.view.SwitchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class InstallYuYue3Activity extends BaseActivity implements View.OnClickListener, SwitchView.OnStateChangedListener {
    private RelativeLayout goto_photo;
    private ImageView img;
    private SwitchView sw_need;
    private String pid;
    private String type;
    private TextView chengshi, time, select_project, price, style, areas, tv_invoice, danwei;
    private EditText tel, realname, area, address, yusuan_price, tv_remark;

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("提交预约");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        ImageView ic_telephone = (ImageView) findViewById(R.id.ic_telephone);
        ic_telephone.setOnClickListener(this);

        ic_telephone.setVisibility(View.GONE);
    }

    private int num = 0;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_install_yu_yue);
        EventBus.getDefault().register(this);
       // MyApplication.getInstance().addDestoryActivity(this, "yuyue3");
        initTitle();
        num = getIntent().getIntExtra("num", 0);
        tv_invoice = (TextView) findViewById(R.id.tv_invoice);

        initJsonData();
        areas = (TextView) findViewById(R.id.areas);
        pid = getIntent().getStringExtra("pid");
        type = getIntent().getStringExtra("type");
        goto_photo = (RelativeLayout) findViewById(R.id.goto_photo);
        goto_photo.setOnClickListener(this);
        img = (ImageView) findViewById(R.id.img);
        img.setOnClickListener(this);
        sw_need = (SwitchView) findViewById(R.id.sw_need);//发票信息
        sw_need.setOpened(false);
        sw_need.setOnStateChangedListener(this);
        rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        rl_message.setOnClickListener(this);
        findViewById(R.id.sub).setOnClickListener(this);
        findViewById(R.id.ll_chengshi).setOnClickListener(this);
        findViewById(R.id.ll_project).setOnClickListener(this);
        findViewById(R.id.ll_time).setOnClickListener(this);
        select_project = (TextView) findViewById(R.id.select_project);
        budgetid = getIntent().getStringExtra("budgetid");
        if (null == budgetid) {
            budgetid = "";
        } else {
            select_project.setText("" + getIntent().getStringExtra("name"));
        }

        chengshi = (TextView) findViewById(R.id.chengshi);
        price = (TextView) findViewById(R.id.price);
        DecimalFormat df = new DecimalFormat("######0.00");
        danwei = (TextView) findViewById(R.id.danwei);
        if (null != getIntent().getStringExtra("danwei")) {
            danwei.setText(getIntent().getStringExtra("danwei"));
        }
        area = (EditText) findViewById(R.id.area);
        try {
            price.setText(df.format(num * Double.parseDouble(getIntent().getStringExtra("price"))));
            area.setText(num + "");

            area.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    DecimalFormat df = new DecimalFormat("######0.00");
                    try {
                        num = Integer.parseInt(s.toString());
                        Double b = num * Double.parseDouble(getIntent().getStringExtra("price"));
                        price.setText(df.format(b));
                    } catch (Exception e) {
                        num = 0;
                        price.setText("0");
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        } catch (Exception re) {
            price.setText("0");
        }


        style = (TextView) findViewById(R.id.style);
        time = (TextView) findViewById(R.id.time);
        tel = (EditText) findViewById(R.id.tel);
        realname = (EditText) findViewById(R.id.realname);
        address = (EditText) findViewById(R.id.address);
        yusuan_price = (EditText) findViewById(R.id.yusuan_price);
        tv_remark = (EditText) findViewById(R.id.tv_remark);
        tv_remark.setText("" + (null == getIntent().getStringExtra("remark") == true ? "" : getIntent().getStringExtra("remark")));
    }

    private String province1;
    private String city1;
    private String district1;

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);
                chengshi.setText(tx);
                city1 = options2Items.get(options1).get(options2);
                province1 = options1Items.get(options1).getPickerViewText();
                district1 = options3Items.get(options1).get(options2).get(options3);

            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色.build();
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        if (options1Items.size() == 0) {
            initJsonData();
            return;
        }
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = GetJsonDataUtil.parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.rl_message:
                Intent intent = new Intent(this, SelectFapiaoActivity.class);
                startActivityForResult(intent, 888);
                break;
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.img:
            case R.id.goto_photo:
                showPopmenu(v);
                break;
            case R.id.sub:
                if ("".equals(realname.getText().toString().trim())) {
                    MyToast("请填写您的姓名");
                    return;
                }
                if ("".equals(chengshi.getText().toString().trim())) {
                    MyToast("请选择您的所在城市");
                    return;
                }
                if ("".equals(address.getText().toString().trim())) {
                    MyToast("请填写详细地址");
                    return;
                }
                if ("".equals(tel.getText().toString().trim())) {
                    MyToast("请填写您的手机号");
                    return;
                }
                if ("".equals(area.getText().toString().trim()) || "0".equals(area.getText().toString().trim())) {
                    MyToast("请填写面积(个数)");
                    return;
                }


                upYuYue();
                break;
            case R.id.ll_chengshi:
                ShowPickerView();
                break;
            case R.id.ll_time:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                String[] b = str.split("-");
                Calendar startDate = Calendar.getInstance();
                startDate.set(Integer.parseInt(b[0]), Integer.parseInt(b[1]) - 1, Integer.parseInt(b[2]));
                Calendar endDate = Calendar.getInstance();
                endDate.set(2110, 10, 29);
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String defaultTime = format.format(date);

                        time.setText(defaultTime);
                    }
                })
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                        .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                        .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)//默认全部显示
                        .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                        .setTitleBgColor(getResources().getColor(R.color.white))//标题背景颜色 Night mode
                        .setBgColor(getResources().getColor(R.color.white))//滚轮背景颜色 Night mode
                        .setRangDate(startDate, endDate)//默认是1960-2110年
                        .setDate(startDate)// 默认是系统时间*/
                        .build();
                pvTime.show();
                break;
            case R.id.ll_project:

                Intent intent2 = new Intent(this, SelectXiangmu.class);
                startActivityForResult(intent2, 999);

                break;
        }
    }

    private String budgetid = "";

    private void upYuYue() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", type);
        map.put("pid", pid);
        if (!"".equals(budgetid))
            map.put("budgetid", budgetid);

        map.put("realname", realname.getText());
        map.put("tel", tel.getText());
        map.put("province", province1);
        map.put("city", city1);
        map.put("district", district1);
        if (!"".equals(address.getText()))
            map.put("address", address.getText());
        if (!"".equals(yusuan_price.getText()))
            map.put("yusuan", yusuan_price.getText());
        if (!"".equals(style.getText()))
            map.put("style", style.getText());
        if (!"".equals(time.getText()))
            map.put("service_time", time.getText());
        if (!"".equals(tv_remark.getText()))
            map.put("remark", tv_remark.getText());
        map.put("area", area.getText());
        map.put("nums", area.getText());
        map.put("amount", price.getText());
//        if_receipt是否有发票（0和1）、invoiceId（发票id
        map.put("if_receipt", need);
        if ("1".equals(need)) {
            if ("".equals(invoiceId)) {
                MyToast("请选择发票");
                return;
            }
            map.put("invoiceId", invoiceId);
        }

        if (imagePath != null) {
            String compressImage = BitnapUtils.compressImage(imagePath, imagePath, 30);
            File compressedPic = new File(compressImage);
            map.put("hx_img", compressedPic);
        }

        StringBuffer sb = new StringBuffer("[");
        sb.append("{\n" +
                "            \"type\":\"" + type + "\",\n" +
                "            \"pid\":\"" + pid + "\",\n" +
                "            \"price\":\"" + price.getText().toString() + "\",\n" +
                "            \"nums\":\"" + area.getText() + "\"\n" +
                "        }");

        sb.append("]");
        map.put("json_str", sb.toString());


        showDialog();

        Set keys = map.keySet();
        if (keys != null)

        {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }

        XUtil.Post(Url.DECORATE_MAKEORDER, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Log.i("----", "onSuccess:= " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("result");
                            String info = jsonObject.optString("info");
                            if ("1".equals(res)) {
                                // MyToast(info);
                                Gson gson = new Gson();
                                GoToOrderBean bean = gson.fromJson(result, GoToOrderBean.class);
                                GoToOrderBean.InfoEntity info1 = bean.getInfo();
                                startActivity(new Intent(InstallYuYue3Activity.this, GotoOrderActivity.class).putExtra("info1", info1));
                            } else {
                                if ("-1".equals(res)) {
                                    info = "请重新登录";
                                }
                                MyToast(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        closeDialog();
                        super.onFinished();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        closeDialog();
                        ex.printStackTrace();
                    }
                }

        );

    }

    /**
     * ------头像点击
     */
    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);
                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    //得到的图片地址
    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }
        this.imagePath = imagePath;
        x.image().bind(img, "file://" + imagePath);
        img.setVisibility(View.VISIBLE);
        goto_photo.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    String imagePath = AlbumImagePath.getPath(this, uri);

                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    File file = new File(imagePath);

                    if (!file.exists()) {
                        return;
                    }

                    updateImage(imagePath, uri);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            case 888:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("name");
                    invoiceId = data.getStringExtra("id");
                    tv_invoice.setText(name + "");
                }
                break;
            case 999:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("name");
                    budgetid = data.getStringExtra("id");
                    select_project.setText(name + "");
                }
                break;
            default:
                break;
        }

    }

    private String invoiceId = "";
    private String need = "0";

    @Override
    public void toggleToOn(View view) {
        sw_need.setOpened(true);
        showOrHidePickLayout2(true);
        need = "1";
    }

    private RelativeLayout rl_message;

    private void showOrHidePickLayout2(boolean isNeedToPick) {
        if (isNeedToPick) {
            rl_message.setVisibility(View.VISIBLE);
        } else {
            rl_message.setVisibility(View.GONE);
        }
    }

    @Override
    public void toggleToOff(View view) {
        sw_need.setOpened(false);
        showOrHidePickLayout2(false);
        need = "0";
    }
}
